package com.wzy.oa_sys.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class JwtUtil {
    @Value("${jwt.secret}")
    private String SECRET;


    // 解析 JWT 并获取用户 ID
    public Long getUserIdFromToken(String token) {
        try {
            // 创建算法
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            // 解码 JWT
            DecodedJWT decodedJWT = JWT.require(algorithm)
                    .build()
                    .verify(token);
            // 提取用户 ID
            return decodedJWT.getClaim("userId").asLong();
        } catch (Exception e) {
            e.printStackTrace();
            return null; // 或者抛出自定义异常
        }
    }

    public String getUserRoleFromToken(String token) {
        try {
            // 创建算法
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            // 解码 JWT
            DecodedJWT decodedJWT = JWT.require(algorithm)
                    .build()
                    .verify(token);
            // 提取用户 ID
            return decodedJWT.getClaim("role").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null; // 或者抛出自定义异常
        }
    }

    // 校验 token
    public boolean validateToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWT.require(algorithm).build().verify(token);
            return true; // Token valid
        } catch (Exception e) {
            return false; // Token invalid
        }
    }

    // 从 HttpServletRequest 中提取用户 ID
    public Long extractUserId(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        String userId = null;

        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7); // 去掉 "Bearer " 前缀
            Long userIdFromToken = getUserIdFromToken(token);
            userId = String.valueOf(userIdFromToken); // 解析用户 ID
        }
        if(userId == null){
            return 0L;
        }
        return Long.parseLong(userId); // 返回用户 ID，或返回 null
    }

    public String extractUserRole(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        String userIdFromToken = null;

        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7); // 去掉 "Bearer " 前缀
            userIdFromToken = getUserRoleFromToken(token);
        }

        return userIdFromToken; // 返回用户 ID，或返回 null
    }
}
